package HomeService

import (
	"bytes"
	"context"
	"gdshop-font-api-go/app/entity"
	"gdshop-font-api-go/app/request/HomeReq"
	"gdshop-font-api-go/app/response/DiyPageResp"
	"gdshop-font-api-go/library/response"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"gdshop-font-api-go/library/tools/myCache"
	"gdshop-font-api-go/library/tools/mylog"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
	"text/template"
	"time"
)

func Index(ctx context.Context, parames *HomeReq.Index) *response.JsonResponse {
	diyPageItemList := []*entity.DiyPageItem{}
	err := toolsDb.GetUnSafaTable(ctx, "diy_page_item").As("dpi").
		LeftJoin("diy_page dp", "dp.id = dpi.page_id").
		Where("dp.page_type = 1 AND dp.status = 1 AND dp.is_activated = 1 AND dp.delete_at < 1 AND dpi.delete_at < 1 AND dpi.status = 1").
		Fields("dpi.*").Order("dpi.sort DESC").Structs(&diyPageItemList)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	result := []*DiyPageResp.Result{}
	// 解析jsonData
	for _, item := range diyPageItemList {
		result = append(result, &DiyPageResp.Result{
			TypeId: item.TypeId,
			Data:   parsingJsonData(ctx, item.TypeId, item.JsonData),
		})
	}

	return response.SuccessByRequestMessageData(nil, "成功", result)
}

// 处理图片地址，前缀的补充等
func handleTypeDataImgUrl(ctx context.Context, img string) string {
	if strings.Index(img, "http") != -1 {
		return img
	} else {
		return g.Cfg().GetString("site.PhotoUrlProfix") + img
	}
}

func getDiyLinkTmplAll(ctx context.Context, tKey string) string {
	all, err := myCache.GetOrSetFunc("table:diy_link_tmpl_all", func() (interface{}, error) {
		all, err := toolsDb.GetUnSafaTable(ctx, "diy_link_tmpl").All()
		if err != nil {
			return nil, err
		}
		return all, nil
	}, 3600*time.Second)

	if err != nil {
		return ""
	}
	var ltList []*entity.DiyLinkTmpl
	err = gconv.Scan(all, &ltList)
	if err != nil {
		return ""
	}
	if ltList == nil {
		return ""
	}
	for _, item := range ltList {
		if item.Tkey == tKey {
			return item.Tcon
		}
	}
	return ""
}

func getLinkTmpl(ctx context.Context, typeId int, linkStr string) string {
	if typeId == 9999 {
		return ""
	}
	tkey := ""

	if typeId > 8999 {
		// 9000 或者 以上，查询条件 只需要 link
		tkey = linkStr
	} else {
		// 9000 以下 使用 typeId 查询
		tkey = gconv.String(typeId)
	}

	return getDiyLinkTmplAll(ctx, tkey)

	/*switch typeId {
	case 1:
		return "{\"name\":\"goods/details\",\"params\":{\"id\":{{.link}}}}"
	case 2:
		return "{\"name\":\"goods/list\",\"params\":{\"cid\":{{.link}}}}"
	}*/
}

func handleLink(ctx context.Context, item *DiyPageResp.TypeData) string {
	if item.TypeId == 9999 {
		return item.Link
	}
	tmpl, err := template.New("tplname").Parse(getLinkTmpl(ctx, item.TypeId, item.Link))
	if err != nil {
		mylog.ErrorLog("handleLink 链接模板读取错误：", err)
		return ""
	}
	var buf bytes.Buffer
	//模板合并输出
	err = tmpl.Execute(&buf, g.Map{
		"link": item.Link,
	})
	if err != nil {
		mylog.ErrorLog("handleLink 模板渲染错误：", err)
		return ""
	}
	return buf.String()
}

// 解析json 数据
func parsingJsonData(ctx context.Context, typeId int, jsonData string) interface{} {
	j := gjson.New(jsonData)
	switch typeId {
	case 7:
		a := new(DiyPageResp.TypeData7)
		err := j.Struct(a)
		if err != nil {
			return nil
		}
		for _, item := range a.DataList {
			item.Link = handleLink(ctx, item)
			item.Img = handleTypeDataImgUrl(ctx, item.Img)
		}
		return a
	case 3:
		a := new(DiyPageResp.TypeData3)
		err := j.Struct(a)
		if err != nil {
			return nil
		}
		for _, item := range a.DataList {
			item.Img = handleTypeDataImgUrl(ctx, item.Img)
		}
		return a
	case 6:
		a := new(DiyPageResp.TypeData6)
		err := j.Struct(a)
		if err != nil {
			return nil
		}
		for _, item := range a.Pictures {
			item.Img = handleTypeDataImgUrl(ctx, item.Img)
		}
		return a
	case 2:
		a := new(DiyPageResp.TypeData2)
		err := j.Struct(a)
		if err != nil {
			return nil
		}
		for _, item := range a.Photos {
			item.Img = handleTypeDataImgUrl(ctx, item.Img)
		}
		return a
	case 12:
		return j
	case 15, 16:
		return j
	}

	return nil
}
